package com.cp.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cp.core.listener.ExcelDictDtoListener;
import com.cp.core.mapper.DictMapper;
import com.cp.core.pojo.dto.ExcelDictDTO;
import com.cp.core.pojo.entity.Dict;
import com.cp.core.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author ming
 * @since 2022-07-27
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Resource
    private RedisTemplate redisTemplate;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class,new ExcelDictDtoListener(baseMapper)).sheet().doRead();
        log.info("excel导入成功!");
    }

    @Override
    public List<ExcelDictDTO> excelData() {
        List<Dict> dicts = baseMapper.selectList(null);
        List<ExcelDictDTO> excelDtoList = new ArrayList<>(dicts.size());
        for (Dict dict : dicts) {
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            BeanUtils.copyProperties(dict,excelDictDTO);
            excelDtoList.add(excelDictDTO);
        }
        return excelDtoList;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {
        //查询redis是否存在数据列表
        try {
            //redis连接不上我们直接捕获，不要抛出异常，执行下面查询数据库
            List<Dict> dictList = (List<Dict>) redisTemplate.opsForValue().get("dictList:"+parentId);
            if(dictList!=null){
                return dictList;
            }
        } catch (Exception e) {
            log.error("redis服务读取异常:{}", ExceptionUtils.getStackTrace(e));
            e.printStackTrace();
        }
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentId);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //填充hasChildren
        for (Dict dict : dictList) {
            //判断当前节点是否有子节点
            dict.setHasChildren(this.hasChildren(dict.getId()));
        }
        //放入redis
        try {
            redisTemplate.opsForValue().set("dictList:",dictList,5, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis存入异常:{}", ExceptionUtils.getStackTrace(e));
            e.printStackTrace();
        }
        return dictList;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<Dict>().eq("dict_code", dictCode);
        Dict dict = this.baseMapper.selectOne(wrapper);
        return this.listByParentId(dict.getId());
    }

    @Override
    public String getNameByDictCodeAndValue(String dictCode, Integer value) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dict = this.baseMapper.selectOne(wrapper);
        if(dict==null) return "";
        QueryWrapper<Dict> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("parent_id",dict.getId()).eq("value",value).select("name");
        List<Object> objects = this.baseMapper.selectObjs(wrapper1);
        if(objects.size()==0) return "";
        return (String) objects.get(0);


    }

    private boolean hasChildren(Long parentId){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentId);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}
